package com.zivwu.library.widget.progress;


import com.trello.rxlifecycle2.android.ActivityEvent;
import com.trello.rxlifecycle2.android.RxLifecycleAndroid;
import com.zivwu.library.widget.progress.ProgressListener;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.subjects.BehaviorSubject;

/**
 * 延迟展示Progress,提供更好的用户体验
 */
public class ProgressControler implements ProgressListener.Visible {
    private int PROGRESSBAR_DELAY = 300;
    private static final int PROGRESS_COMPLETED = 100;
    private int progressFlag = PROGRESS_COMPLETED;

    BehaviorSubject<ActivityEvent> lifecycle;
    private ProgressListener.Visible visible;
    private Disposable subscribe;


    public ProgressControler(ProgressListener.Visible visible, BehaviorSubject<ActivityEvent> lifecycle) {
        this.visible = visible;
        this.lifecycle = lifecycle;
    }

    public ProgressControler(int PROGRESSBAR_DELAY, ProgressListener.Visible visible, BehaviorSubject<ActivityEvent> lifecycle) {
        this.PROGRESSBAR_DELAY = PROGRESSBAR_DELAY;
        this.visible = visible;
        this.lifecycle = lifecycle;
    }

    @Override
    public void showProgress() {
        progressFlag--;
        if (subscribe == null || subscribe.isDisposed())
            subscribe = Observable.timer(PROGRESSBAR_DELAY, TimeUnit.MILLISECONDS)
                    .observeOn(AndroidSchedulers.mainThread())
                    .compose(RxLifecycleAndroid.<Long>bindActivity(lifecycle))
                    .subscribe(new Consumer<Long>() {
                        @Override
                        public void accept(Long aLong) throws Exception {
                            visible.showProgress();
                        }
                    });

    }

    @Override
    public void removeProgress() {
        progressFlag++;
        if (progressFlag < PROGRESS_COMPLETED)
            return;
        if (subscribe != null && !subscribe.isDisposed()) {
            subscribe.dispose();
        }
    }


    private boolean isShowing() {
        return progressFlag != PROGRESS_COMPLETED;
    }
}
